package com.shengwei.truck.driver.view.ui.task;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.lifecycle.Observer;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.shengwei.truck.driver.bean.MyConstant;
import com.shengwei.truck.driver.utils.MyToast;
import com.shengwei.truck.driver.view.ui.app.MyApplication;
import com.shengwei.truck.driver.R;
import com.shengwei.truck.driver.bean.FileUrlBean;
import com.shengwei.truck.driver.bean.Result;
import com.shengwei.truck.driver.bean.task.JsonTaskDetailData;
import com.shengwei.truck.driver.databinding.ActivityTaskDetailBinding;
import com.shengwei.truck.driver.permission.RxjavaPermissionUtil;
import com.shengwei.truck.driver.utils.CommonUtil;
import com.shengwei.truck.driver.utils.DateTimeUtils;
import com.shengwei.truck.driver.utils.IntentConstants;
import com.shengwei.truck.driver.utils.MyLogCat;
import com.shengwei.truck.driver.view.adapter.task.TaskGridAdapter;
import com.shengwei.truck.driver.view.selfview.stepview.StepAdapter;
import com.shengwei.truck.driver.view.selfview.stepview.StepData;
import com.shengwei.truck.driver.view.ui.BaseActivity;
import com.shengwei.truck.driver.view.ui.MainActivity;
import com.shengwei.truck.driver.view.ui.common.MyAlertDlg;
import com.shengwei.truck.driver.view.ui.common.ScalePhotoActivity;
import com.shengwei.truck.driver.view.ui.task.pounds.PostPoundsListActivity;
import com.shengwei.truck.driver.vm.TaskDetailViewModel;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 任务详情页
 */
public class TaskDetailActivity extends BaseActivity<TaskDetailViewModel, ActivityTaskDetailBinding> implements View.OnClickListener {
    private static final String TAG = TaskDetailActivity.class.getSimpleName() ;
    String mTaskId;
    String mTaskNo; //任务号，也要传递到‘磅单上传页面’
    String mUnit; //“重量”单位要传递给磅单上传页面
    private String mQrCodeUrl;
    private PopupWindow mSharePopupWindow;
    private ArrayList<StepData> mDataList;
    private long mLeftTime; //二维码过时剩余时间
    private Disposable mDisposable;

    //显示出货与收货图片列表
    private TaskGridAdapter mAdapterOut;
    private TaskGridAdapter mAdapterRecv;
    private ArrayList<FileUrlBean> mOutPoundsImgs;
    private ArrayList<FileUrlBean> mRecvPoundsImgs;
    private String mCarNum;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        JsonTaskDetailData detailData = new JsonTaskDetailData();
        mDataBinding.setTaskDetail(detailData);
        getLastIntent();
        initView();
        initLiveDataObersve();
    }

    @Override
    protected void onStart() {
        if(mTaskId != null){
            mViewModel.getTaskDetail(mTaskId);
        }
        super.onStart();
    }

    @Override
    protected void onStop() {
        if(mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
            mDisposable = null;
        }
        super.onStop();
    }
    /**
     * 初始化控件显示
     */
    private void initView() {
        intStepData();
        mDataBinding.contactCommonLayout.contactDetailDivider.setVisibility(View.GONE);

        mDataBinding.tvCancelTask.setOnClickListener(this);
        mDataBinding.btAccepTask.setOnClickListener(this);
        mDataBinding.btPostPoundsList.setOnClickListener(this);

        mDataBinding.contactCommonLayout.loadUnloadAddress.imvPublishPhone.setOnClickListener(this);
        mDataBinding.contactCommonLayout.loadUnloadAddress.tvPublishPhone.setOnClickListener(this);

        mDataBinding.contactCommonLayout.loadUnloadAddress.tvReceiverPhone.setOnClickListener(this);
        mDataBinding.contactCommonLayout.loadUnloadAddress.imvRecvPhone.setOnClickListener(this);

        mDataBinding.tvDispatchPhone.setOnClickListener(this);
        mDataBinding.imvDispatchPhone.setOnClickListener(this);

        setTextMarquee(mDataBinding.tvDestPerson);
    }


    /**
     * 各阶段上的标注文字
     */
    private void intStepData() {
        StepData data1 = new StepData();
        data1.setStepText("已接");
        StepData data2 = new StepData();
        data2.setStepText("提货");
        StepData data3 = new StepData();
        data3.setStepText("运输");
        StepData data4 = new StepData();
        data4.setStepText("磅单");
        StepData data5 = new StepData();
        data5.setStepText("完成");
        mDataList = new ArrayList<>();
        mDataList.add(data1);
        mDataList.add(data2);
        mDataList.add(data3);
        mDataList.add(data4);
        mDataList.add(data5);

        //StepView与Activity通信，通过接口回调的方式
        mDataBinding.stepView.setStepAdapter(new StepAdapter() {
            @Override
            public int getCount() {
                return mDataList.size();
            }
            @Override
            public List<StepData> getData() {
                return mDataList;
            }
        });
    }

    /**
     * 创建liveData观察者，用于监听数据变化，从而更新UI
     */
    private void initLiveDataObersve() {

        //监听撤销任务
        mViewModel.getCancelTaskLiveData().observe(this, new Observer<Result<String>>() {
            @Override
            public void onChanged(Result<String> cancelResult) {
                cancelResult.handler(new OnCallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                        String cancelTaskOk = TaskDetailActivity.this.getResources().getString(R.string.cancel_task_ok);
                        MyToast.showToastCenter(new WeakReference<>(TaskDetailActivity.this),cancelTaskOk,Toast.LENGTH_SHORT,true);
                        finish();
                    }
                    @Override
                    public void onFailure(String msg) {
                        String[] errMsg = msg.split(";");
                        if(errMsg != null && errMsg.length > 1) {
                            int code = Integer.valueOf(errMsg[0]);
                            String msgCotnent = errMsg[1];
                            if(code == 4050){
                                dealCancelTaskTip(msgCotnent);
                            }
                            else{
                                super.onFailure(msg);
                            }
                        }
                    }
                });
            }
        });

        //监听获取任务详情的数据
        mViewModel.getTaskDetailLiveData().observe(this, new Observer<Result<JsonTaskDetailData>>() {
            @Override
            public void onChanged(Result<JsonTaskDetailData> result) {
                result.handler(new OnCallback<JsonTaskDetailData>() {
                    @Override
                    public void onSuccess(JsonTaskDetailData data) {
                        mTaskNo = data.taskNo;
                        mUnit = data.unit; //单位默认为吨
                        mCarNum = data.getVehiclePlateNumber();
                       // data.laName = MyConstant.testCustomName; //gxw+要删除恢复
                       // data.uaName = MyConstant.testCustomName; //gxw+要删除恢复
                        mDataBinding.setTaskDetail(data);
                        refreshDetailView(data);
                    }
                });
            }
        });

        //监听接  “受任务接”  口的数据
        mViewModel.getRecvTaskLiveData().observe(this, new Observer<Result<String>>() {
            @Override
            public void onChanged(Result<String> result) {
                result.handler(new OnCallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                        //接受任务成功
                        String recvOk = TaskDetailActivity.this.getResources().getString(R.string.recv_task_ok);
                        MyToast.showToastCenter(new WeakReference<>(TaskDetailActivity.this),recvOk,Toast.LENGTH_SHORT,true);
                        updateViewForRecvOK();
                        //保存当前任务
                        saveCurTask(mTaskId,"0","0");
                        //跳转到首页
                        goMainActivity();
                        TaskDetailActivity.this.finish();
                    }
                });
            }
        });
    }


    /**
     * 处理 “失败撤销任务”
     */
    public void dealCancelTaskTip(String msgContent){

        MyAlertDlg.alertConfirmTip2(0,msgContent,TaskDetailActivity.this, new MyAlertDlg.AlerClickInterface() {
                    @Override
                    public void cancel() {
                    }
                    @Override
                    public void sure(){
                    }
                });
    }

    /**
     * 保存当前任务信息
     * @param taskId：任务ID
     * @param isLocation:是否定位
     * @param weightStatus：可定位状态
     */
    public void saveCurTask(String taskId,String isLocation,String weightStatus){
        //保存当前正在进行的任务ID
        WeakReference<Context> contextWeakReference = new WeakReference<>(TaskDetailActivity.this);
        MyApplication.getInstance().saveCurTask(contextWeakReference.get(),taskId,isLocation,weightStatus);
        MyLogCat.i(TAG,"curTaskId="+mTaskId);
    }

    public void goMainActivity() {
        Intent i = new Intent(TaskDetailActivity.this, MainActivity.class);
        i.putExtra("tabIndex",0);
        startActivity(i);
    }

    /**
     * 接受任务成功后，显示或隐藏某些UI
     */
    private void updateViewForRecvOK() {
        showHasRecvTaskStep();
    }

    /**
     * 更新二维码状态文本
     */
    private void updtQrcodeStateText(int taskStatusCode){
        WeakReference<Context> contextWeakReference = new WeakReference<Context>(this);
        String taskText = CommonUtil.getStateByCode(taskStatusCode,contextWeakReference);
        mDataBinding.tvQrCodeStatus.setText(taskText);
    }

    /**
     * 显示与隐藏 联系方式相关界面，因为有时候 “卸货地址为空”
     *  或 “厂家联系方式为空”，则要隐藏对应的UI。
     * @param detailData
     */
    private void showHideContactUI(JsonTaskDetailData detailData){
        //卸货地址，不为空再显示对应的界面
        if(!TextUtils.isEmpty(detailData.unloadingCityName)){
            mDataBinding.contactCommonLayout.loadUnloadAddress.tvUnLoadDetailAddress.setVisibility(View.VISIBLE);
        }
        //厂商联系方式为空，则隐藏对应的界面
        if(TextUtils.isEmpty(detailData.factoryLinkPhone)){
            mDataBinding.contactCommonLayout.loadUnloadAddress.imvPublishPhone.setVisibility(View.GONE);
            mDataBinding.contactCommonLayout.loadUnloadAddress.tvPublishPhone.setVisibility(View.GONE);
        }
    }

    /**
     * 刷新部分显示，因为其它静态字段已用DataBinding绑定
     * @param detailData 服务器返回的详情数据
     */
    private void refreshDetailView(JsonTaskDetailData detailData) {
        if(detailData != null) {
            //出厂、收货磅单图片,二维码图片URL
            mOutPoundsImgs = detailData.outWeighingListUrls;
            mRecvPoundsImgs = detailData.receiveWeighingListUrls;
            mQrCodeUrl = detailData.qrCodeUrl;

            showHideContactUI(detailData);
            //更新二维码状态文本
            int taskStatusCode = detailData.taskStatus;
            int showRecvButton = detailData.showButton;
            updtQrcodeStateText(taskStatusCode);
            showHideRecvButton(showRecvButton);
            switch (taskStatusCode) {
                case 0: //未接任务
                    showNoTaskStep(showRecvButton);
                    showShareButton();
                    break;
                case 1: //已接任务
                    showHasRecvTaskStep();
                    mLeftTime = detailData.lastTime;
                    showLeftTime(mLeftTime);  //提货二维码超时时间
                    break;
                case 2: //已提货-运输阶段
                    showTransportStep();
                    break;
                case 3: //已提交磅单
                case 4://重新提交磅单
                case 5: //已完成
                    showHasCompleteStep(mOutPoundsImgs,mRecvPoundsImgs);
                    break;
                default:  //任务超时，任务撤销等状态
                    dealOtherState();
            }
            //更新 “转派、分享”面板
            updateShareForward(detailData);
            //回显已经上传的磅单（出厂，或者 出厂+收货磅单）
            showHasPostPoundsStep(mOutPoundsImgs,mRecvPoundsImgs);
        }
    }

    public void dealOtherState(){
        mDataBinding.qrcodeLayout.setVisibility(View.GONE);
    }

    //更新分享，转派面板
    public void updateShareForward(JsonTaskDetailData taskDetail) {
        if(taskDetail.transfer == 1 || taskDetail.share == 1) {
            mDataBinding.forwardOrShareLayout.setVisibility(View.VISIBLE);
            //转派
            if(taskDetail.transfer == 1){
                mDataBinding.tvTaskShareForward.setBackgroundResource(R.drawable.shape_forward_tag_bg);
                mDataBinding.tvTaskShareForward.setText(R.string.forward);
                CommonUtil.loadRoundPic(taskDetail.userAvatar,mDataBinding.imvLeft,getApplicationContext());
                CommonUtil.loadRoundPic(taskDetail.transferUserAvatar,mDataBinding.imvRight,getApplicationContext());
            }
            //分享
            if(taskDetail.share == 1){
                mDataBinding.tvTaskShareForward.setBackgroundResource(R.drawable.shape_share_tag_bg);
                mDataBinding.tvTaskShareForward.setText(R.string.share);
                CommonUtil.loadRoundPic(taskDetail.userAvatar,mDataBinding.imvLeft,getApplicationContext());
                CommonUtil.loadRoundPic(taskDetail.shareUserAvatar,mDataBinding.imvRight,getApplicationContext());
            }
            //设置跑马灯效果，因文字过长
            mDataBinding.tvDestPerson.requestFocus();
            setTextMarquee(mDataBinding.tvDestPerson);
            setTextMarquee(mDataBinding.tvFromPerson);
        }
    }

    /**
     * 显示分享转派按钮
     */
    public void showShareButton() {
        TextView tvBtRightShare = mToolbar.findViewById(R.id.tvBtRightShare);
        tvBtRightShare.setVisibility(View.VISIBLE);
        tvBtRightShare.setOnClickListener(this);
    }

    /**
     * 显示 "未接任务" 阶段的UI
     */
    public void showNoTaskStep(int showRecvButton) {
        mDataBinding.stepView.setSelectPosition(-1);
        //显示接受任务按钮
        if(showRecvButton == 1){
            mDataBinding.btAccepTask.setVisibility(View.VISIBLE);
        }
        else{
            mDataBinding.btAccepTask.setVisibility(View.GONE);
        }
        mDataBinding.qrcodeLayout.setVisibility(View.VISIBLE);
        //显示可撤销任务按钮
        mDataBinding.tvCancelTask.setVisibility(View.VISIBLE);

        //隐藏磅单按钮
        mDataBinding.btPostPoundsList.setVisibility(View.GONE);
    }

    /**
     * 显示隐藏 接受任务按钮
     * @param showRecvButton: 1显示接受任务按钮，0隐藏
     */
    public void showHideRecvButton(int showRecvButton){
        if(showRecvButton == 1){
            mDataBinding.btAccepTask.setVisibility(View.VISIBLE);
        }
        else{
            mDataBinding.btAccepTask.setVisibility(View.GONE);
        }
    }

    /**
     * 显示 "已接任务" 阶段的UI
     */
    public void showHasRecvTaskStep() {
        //显示提货二维码
        mDataBinding.qrcodeLayout.setVisibility(View.VISIBLE);
        mDataBinding.tvQrShowTip.setVisibility(View.GONE);
        Glide.with(getApplicationContext()).load(mQrCodeUrl).into( mDataBinding.imvQrcode);

        mDataBinding.tvCancelTask.setVisibility(View.VISIBLE);  //可撤销任务
        mDataBinding.stepView.setSelectPosition(0);       //显示物流进度
        mDataBinding.btAccepTask.setVisibility(View.GONE);     //已接受任务，则隐藏接受按钮

        //隐藏  接受任务按钮 与  上传磅单按钮（扫码提货后再显示上传磅单）
        mDataBinding.bottomButtonLayout.setVisibility(View.GONE);

    }

    /**
     * 显示二维码提货 剩余时间
     */
    public void showLeftTime(long leftMillsTime) {
        mDataBinding.leftTimeLayout.setVisibility(View.VISIBLE);
        String strLeftTime = getLeftTimeStr(leftMillsTime);
        if(!TextUtils.isEmpty(strLeftTime)){
            mDataBinding.tvLeftTime.setText(strLeftTime);
            startTimeDown();
        }
    }

    /**
     * 开始倒计时，每隔1秒后执行
     */
    public void startTimeDown() {
        mDisposable =  Observable.interval(1, TimeUnit.SECONDS)
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        MyLogCat.i(TAG,String.valueOf(aLong));
                        mLeftTime -= 1000;
                        String strLeftTime = getLeftTimeStr(mLeftTime);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mDataBinding.tvLeftTime.setText(strLeftTime);
                            }
                        });
                    }
                });
    }
    /**
     * 将剩余时间毫秒值 转为 hh:mm:ss
     * @param leftMillsTime
     * @return
     */
    public String getLeftTimeStr(long leftMillsTime){
        String strLeftTime;
        if(leftMillsTime > 0){
            strLeftTime = DateTimeUtils.getGapTime(leftMillsTime);
        }
        else{
            strLeftTime = TaskDetailActivity.this.getResources().getString(R.string.has_due);
        }
        return strLeftTime;
    }
    /**
     * 显示 “已扫码” 提货
     */
    public void showHasGetGoodsStep() {
        //显示物流进度条
        showHasRecvTaskStep();
        int colorPrimary = this.getResources().getColor(R.color.colorPrimary);
        mDataBinding.stepView.setSelectPosition(1);

        //隐藏二维码和接受任务按钮
        mDataBinding.imvQrcode.setVisibility(View.GONE);
        mDataBinding.tvQrCodeStatus.setText(R.string.qr_has_get_goods);
        mDataBinding.btAccepTask.setVisibility(View.GONE);
        //显示榜单按钮
        mDataBinding.btPostPoundsList.setVisibility(View.VISIBLE);
        mDataBinding.btPostPoundsList.setEnabled(true);
        ////显示出厂重量字段
        mDataBinding.leftRecvWeightLayout.setVisibility(View.VISIBLE);
        mDataBinding.tvLeftFactoryWeightLabel.setVisibility(View.VISIBLE);
        mDataBinding.tvLeftFactoryWeight.setVisibility(View.VISIBLE);

    }

    /**
     * 显示“运输”状态下的UI
     */
    public void showTransportStep() {
        //运输状态下，已经扫描过二维码，则隐藏二维码布局 与接受任务按钮
        mDataBinding.qrcodeLayout.setVisibility(View.GONE);
        mDataBinding.btAccepTask.setVisibility(View.GONE);
        //显示上传磅单按钮
        mDataBinding.btPostPoundsList.setVisibility(View.VISIBLE);
        mDataBinding.stepView.setSelectPosition(2);
    }

    /**
     * 显示“榜单全部已提交”状态（目前是状态值为3和4的情况下）下的UI
     */
    public void showHasPostPoundsStep(ArrayList<FileUrlBean> outFactoryPoundsUrls,ArrayList<FileUrlBean> recvPoundsUrls) {
        RequestOptions requestOptions = new RequestOptions();
        requestOptions.placeholder(R.mipmap.ic_launcher);
        requestOptions.error(R.mipmap.ic_launcher);
        //显示"出厂榜单" 与 "收货榜单"图片
        if(outFactoryPoundsUrls != null && outFactoryPoundsUrls.size() > 0){
            mDataBinding.outPoundsShowLayout.setVisibility(View.VISIBLE);
            showOutImgGrid(outFactoryPoundsUrls);
        }
        if(recvPoundsUrls != null && recvPoundsUrls.size() > 0){
            mDataBinding.recvPoundsShowLayout.setVisibility(View.VISIBLE);
            showRecvImgGrid(recvPoundsUrls);
        }
    }

    /**
     * 显示出厂图片选择列表
     */
    public void showOutImgGrid(ArrayList<FileUrlBean> fileUrls){
        mDataBinding.gridOutPoundsList.setSelector(new ColorDrawable(Color.TRANSPARENT));
        mAdapterOut = new TaskGridAdapter(this, fileUrls);
        mDataBinding.gridOutPoundsList.setAdapter(mAdapterOut);
        mDataBinding.gridOutPoundsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                goPhotoGallyActivity(position,mOutPoundsImgs);

          /*      String photoUrl = mOutPoundsImgs.get(position).getFileUrl();
                goScalePhotoActivity(photoUrl);*/
            }
        });
    }
    /**
     * 显示收货图片选择列表
     */
    public void showRecvImgGrid(ArrayList<FileUrlBean> fileUrls){
        mDataBinding.gridRecvPoundsList.setSelector(new ColorDrawable(Color.TRANSPARENT));
        mAdapterRecv = new TaskGridAdapter(this, fileUrls);
        mDataBinding.gridRecvPoundsList.setAdapter(mAdapterRecv);
        mDataBinding.gridRecvPoundsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                goPhotoGallyActivity(position,mRecvPoundsImgs);
             /*   String photoUrl = mRecvPoundsImgs.get(position).getFileUrl();
                goScalePhotoActivity(photoUrl);*/
            }
        });
    }

    public void goPhotoGallyActivity(int curPosition,ArrayList<FileUrlBean> imgUrls){
        Intent intent = new Intent(TaskDetailActivity.this, PhotoGallyActivity.class);
        intent.putExtra(IntentConstants.EXTRA_IMAGE_LIST, (Serializable) imgUrls);
        intent.putExtra(IntentConstants.EXTRA_CURRENT_IMG_POSITION, curPosition);
        startActivity(intent);
    }

    public void goScalePhotoActivity(String photoUrl){
        Intent intent = new Intent(TaskDetailActivity.this, ScalePhotoActivity.class);
        intent.putExtra("photoUrl",photoUrl);
        startActivity(intent);
    }

    /**
     * 显示"已完成"状态的任务进度
     */
    public void showHasCompleteStep(  ArrayList<FileUrlBean> outPoundsUrls,ArrayList<FileUrlBean>  recvPoundsUrls) {
        mDataBinding.stepView.setSelectPosition(4);
        //隐藏二维码布局，上传磅单按钮
        mDataBinding.btPostPoundsList.setVisibility(View.GONE);
        mDataBinding.qrcodeLayout.setVisibility(View.GONE);
        //显示收货重量字段
        mDataBinding.tvRecvWeightLabel.setVisibility(View.VISIBLE);
        mDataBinding.tvRecvWeight.setVisibility(View.VISIBLE);
        showHasPostPoundsStep(outPoundsUrls,recvPoundsUrls);

    }
    /**
     * 获取上一页的数据
     */
    public void getLastIntent() {
        Intent i = this.getIntent();
        Bundle bundle = i.getExtras();
        if(bundle != null) {
            mTaskId = bundle.getString("id");
        }
    }

    public  void setTextMarquee(TextView textView) {
        if (textView != null) {
            textView.setEllipsize(TextUtils.TruncateAt.MARQUEE);
            textView.setMarqueeRepeatLimit(-1);
            textView.setSingleLine(true);
            textView.setSelected(true);
            textView.setFocusable(true);
            textView.setFocusableInTouchMode(true);
        }
    }
    @Override
    public int getContentViewId() {
        return R.layout.activity_task_detail;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvCancelTask:
                if(!TextUtils.isEmpty(mTaskId)){
                    mViewModel.cancelTask(mTaskId);
                }
                break;
            case R.id.btAccepTask:   //司机接受任务
                if(!TextUtils.isEmpty(mTaskId)) {
                    MyLogCat.i(TAG,"去接任務");
                    MyAlertDlg.alertConfirmTip(0,R.string.is_sure_recv_task,TaskDetailActivity.this, new MyAlertDlg.AlerClickInterface() {
                        @Override
                        public void cancel() {
                        }
                        @Override
                        public void sure() {
                            mViewModel.recvTaskDetail(mTaskId,1);  //1表示去接任务
                        }
                    });
                }
                break;
            case R.id.tvBtRightShare:  //分享，转派
                showPopupWindow(v);
                break;
            case R.id.tvForward:  //转派
                goShareForward(1);
                break;
            case R.id.tvShare:  //共享
                goShareForward(2);
                break;
            case R.id.imvPublishPhone:
            case R.id.tvPublishPhone:
                String publishPhone = mDataBinding.contactCommonLayout.loadUnloadAddress.tvPublishPhone.getText().toString();
                if(!TextUtils.isEmpty(publishPhone)) {
                    callPhone(publishPhone);
                }
                break;
            case R.id.imvRecvPhone:
            case R.id.tvReceiverPhone:
                String recvPhone = mDataBinding.contactCommonLayout.loadUnloadAddress.tvReceiverPhone.getText().toString();
                if(!TextUtils.isEmpty(recvPhone)) {
                    callPhone(recvPhone);
                }
                break;
            case R.id.imvDispatchPhone:
            case R.id.tvDispatchPhone:
                String dispatchPhone = mDataBinding.contactCommonLayout.tvDispatchPhone.getText().toString();
                if(!TextUtils.isEmpty(dispatchPhone)) {
                    callPhone(dispatchPhone);
                }
                break;
            case R.id.btPostPoundsList: //上传榜单
                Intent i = new Intent(TaskDetailActivity.this, PostPoundsListActivity.class);
                i.putExtra("fromPage",1);
                i.putExtra("taskId",mTaskId);
                i.putExtra("taskNo",mTaskNo);
                i.putExtra("unit",mUnit);
                i.putExtra("carNum",mCarNum);
                startActivity(i);
                break;
        }
    }

    /**
     * 拨打电话
     * @param phone
     */
    private void callPhone(final String phone) {

        //申请多个权限，当所有权限操作完后（批处理），才回调用accept函数，进而才能知道哪个权限被允许了，哪个权限被禁止了。
        final String[] permissionCall = {Manifest.permission.CALL_PHONE};
        RxPermissions permissions = new RxPermissions(this);
        permissions.setLogging(true);
        permissions.requestEach(permissionCall)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        MyLogCat.i(TAG, "checkPermissionRequestEach--:" + "-permission-:" + permission.name + "---------------");
                        if (permission.name.equalsIgnoreCase(Manifest.permission.CALL_PHONE)) {
                            if (permission.granted) {//同意后调用
                                MyLogCat.i(TAG, "checkPermissionRequestEach--:" + "-READ_EXTERNAL_STORAGE-:" + true);
                                Intent intent = new Intent(); // 意图对象：动作 + 数据
                                intent.setAction(Intent.ACTION_CALL); // 设置动作
                                Uri data = Uri.parse("tel:" + phone); // 设置数据
                                intent.setData(data);
                                TaskDetailActivity.this.startActivity(intent); // 激活Activity组件
                            } else if (permission.shouldShowRequestPermissionRationale){//禁止，但没有选择“以后不再询问”，以后申请权限，会继续弹出提示
                                MyLogCat.i(TAG, "checkPermissionRequestEach--:" + "-READ_EXTERNAL_STORAGE-shouldShowRequestPermissionRationale:" + false);
                            }else {//禁止，但选择“以后不再询问”，以后申请权限，不会继续弹出提示
                                MyLogCat.i(TAG, "checkPermissionRequestEach--:" + "-READ_EXTERNAL_STORAGE-:" + false);
                                Toast.makeText(TaskDetailActivity.this, R.string.call_failed, Toast.LENGTH_SHORT).show();
                                RxjavaPermissionUtil.getInstance().alertOpenNavPermission(TaskDetailActivity.this,permissionCall);

                            }
                        }
                    }
                });
    }
    /**
     * 去分享，0指派, 1分享
     *
     * @param pageFrom
     */
    public void goShareForward(int pageFrom) {
        if(mSharePopupWindow != null && mSharePopupWindow.isShowing()) {
            mSharePopupWindow.dismiss();
            mSharePopupWindow = null;
        }
        Intent i = new Intent(TaskDetailActivity.this, ShareForwardActivity.class);
        i.putExtra("pageFrom",pageFrom);
        i.putExtra("id",mTaskId);
        startActivity(i);
    }
    /**
     * 点击按钮，弹出PopupWindow,菜单展示在按钮下面
     * @param view
     */
    private void showPopupWindow(View view){

        View contentView = getLayoutInflater().inflate(R.layout.activity_popupwindow, null);//弹出菜单布局
        if(mSharePopupWindow == null) {
            mSharePopupWindow = new PopupWindow(contentView, WindowManager.LayoutParams.WRAP_CONTENT,
                    WindowManager.LayoutParams.WRAP_CONTENT,true);
        }
        mSharePopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mSharePopupWindow.setOutsideTouchable(true);
        mSharePopupWindow.setTouchable(true);
        mSharePopupWindow.setAnimationStyle(R.style.pop_add);
        int xOff = -CommonUtil.dipsToPixels(getApplicationContext(),100);
        int yOff = -10;
        MyLogCat.i(TAG,"xOff="+xOff+",yOff="+yOff);
        //单击菜单项，进入下一页面
        TextView tvShare = contentView.findViewById(R.id.tvShare);
        TextView tvForward = contentView.findViewById(R.id.tvForward);
        tvShare.setOnClickListener(this);
        tvForward.setOnClickListener(this);
        mSharePopupWindow.showAsDropDown(view,-150,yOff);
    }
}